package fun.codedesign.jdk.thread;

/**
 * 三个线程顺序打印 1 2 3
 *
 * @author zengjian
 * @create 2018-03-20 8:39
 * @since 1.0.0
 */
public class ThreadPrintOrder {

    private static Object obj = new Object();
    private static boolean a = true;
    private static boolean b = false;
    private static boolean c = false;

    public static void main(String[] args) {
        Thread t1 = new Thread2();
        Thread t2 = new Thread3();
        Thread t3 = new Thread4();
        t3.start();
        t2.start();
        t1.start();
    }

    static class Thread2 extends Thread {

        @Override
        public void run() {
            synchronized (obj) {
                while (!a) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("1");
                obj.notifyAll();
                b = true;
            }
        }
    }

    static class Thread3 extends Thread {
        @Override
        public void run() {
            synchronized (obj) {
                while (!b) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("2");
                c = true;
                obj.notifyAll();
            }
        }
    }

    static class Thread4 extends Thread {
        @Override
        public void run() {
            synchronized (obj) {
                while (!c) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("3");
            }
        }
    }
}
